import { OrderService } from "@mallfoundry/order"
import { Form, Modal, Select } from "antd"
import * as _ from "lodash"
import * as React from "react"
import { useState } from "react"

const reasons = [
  "无法联系上买家",
  "买家误拍或重拍了",
  "买家无诚意完成交易",
  "已经缺货无法交易",
]

interface OrderDeclineModalProps {
  visible?: boolean
  orderId: string
  onCancel?: () => void
  onDeclined?: () => void
}

export function OrderDeclineModal(props: OrderDeclineModalProps) {
  const { Option } = Select
  const { visible, orderId, onCancel, onDeclined } = props
  const layout = {
    labelCol: { span: 4 },
    wrapperCol: { span: 19 },
  }
  const [form] = Form.useForm()

  const [loading, setLoading] = useState(false)

  function handleOk() {
    setLoading(true)
    form.validateFields()
      .then(value => value["reason"])
      .then(reason => OrderService.declineOrder(orderId, reason))
      .then(onDeclined)
      .finally(() => setLoading(false))
  }

  return (
    <Modal
      title="取消订单"
      visible={visible}
      maskClosable={false}
      onCancel={onCancel}
      confirmLoading={loading}
      onOk={handleOk}>
      <Form {...layout} form={form} name="cancel-order">
        <Form.Item label="取消原因" name="reason"
                   rules={[{ required: true, message: "请选择原因!" }]}>
          <Select placeholder="请选择一个原因">
            {_.map(reasons, reason =>
              <Option key={reason} value={reason} children={reason}/>)}
          </Select>
        </Form.Item>
      </Form>
    </Modal>)
}
